package com.alibaba.citrus.cr.mn.order.center.facade.adapter.impl;

import com.alibaba.citrus.cr.common.enums.ordercenter.FulfillmentReasonEnum;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.FulfillmentOrderAbilityAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.FulfillmentOrderBatchGetRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.FulfillmentOrderSearchOrderRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.SearchFulfullmentOrderRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.FulfillmentDetailGetResDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.FulfillmentGetResDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.FulfillmentOrderDetailResDTO;
import com.alibaba.cloud.retail.delivery.api.model.delivery.enums.FulfillmentDetailStatusEnum;
import com.alibaba.cloud.retail.delivery.api.model.delivery.enums.FulfillmentDirectionTypeEnum;
import com.alibaba.cloud.retail.delivery.api.model.delivery.request.fulfillment.BatchGetReq;
import com.alibaba.cloud.retail.delivery.api.model.delivery.request.fulfillment.CancelOrderInnerReq;
import com.alibaba.cloud.retail.delivery.api.model.delivery.request.fulfillment.SearchOrderDetailReq;
import com.alibaba.cloud.retail.delivery.api.model.delivery.request.fulfillment.SearchOrderReq;
import com.alibaba.cloud.retail.delivery.api.model.delivery.response.fulfillment.*;
import com.alibaba.cloud.retail.delivery.api.model.fulfillment.request.SearchFulfillmentOrderInnerReq;
import com.alibaba.cloud.retail.delivery.api.model.fulfillment.request.SearchFulfullmentOrderReq;
import com.alibaba.cloud.retail.delivery.api.service.bcfulfillment.FulfillmentOrderAbilityService;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.mnordercenter.orderbaserequest.OrderAtomUpdateResponse;
import io.swagger.models.auth.In;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description 履约单服务适配层
 * @Author zhangjian
 * @Date 2024/1/20 13:42
 */
@Service
public class FulfillmentOrderAbilityAdapterImpl implements FulfillmentOrderAbilityAdapter {

    private static final Log log = Log.getLogger(FulfillmentOrderAbilityAdapter.class);

    @DubboReference
    private FulfillmentOrderAbilityService fulfillmentOrderAbilityService;

    @Override
    public Result<FulfillmentGetResponse> getOne(SearchOrderDetailReq request) {
//        com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<FulfillmentGetResponse> result = fulfillmentOrderAbilityService.getOne(request);
        return null;
    }

    @Override
    public Result<List<FulfillmentOrderDetailResDTO>> searchList(FulfillmentOrderSearchOrderRequest orderRequest) {
        SearchFulfillmentOrderInnerReq searchFulfillmentOrderInnerReq = new SearchFulfillmentOrderInnerReq();
        BeanUtils.copyProperties(orderRequest, searchFulfillmentOrderInnerReq);
        log.info("FulfillmentOrderAbilityAdapterImpl#searchList searchOrderReq={}", JSON.toJSONString(searchFulfillmentOrderInnerReq));
        com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<List<FulfillmentGetRes>> result = fulfillmentOrderAbilityService.searchFulfillmentOrderInner(searchFulfillmentOrderInnerReq);
        log.info("FulfillmentOrderAbilityAdapterImpl#searchList result={}", JSON.toJSONString(result));

        Result<List<FulfillmentOrderDetailResDTO>> resultDto = new Result<>();
        if (CollectionUtils.isEmpty(result.getResult())) {
            resultDto.setSuccess(false);
            resultDto.setErrorCode("OC-01-004-01-16-002");
            resultDto.setMessage("查询履约单失败");
            return resultDto;
        }
        List<FulfillmentOrderDetailResDTO> fulfillmentOrderDetailDtoList = new ArrayList<>();
        result.getResult().forEach(order -> {
            fulfillmentOrderDetailDtoList.addAll(Optional.ofNullable(order.getDetailList()).orElse(Lists.newArrayList()).stream().map(line -> {
                FulfillmentOrderDetailResDTO fulfillmentOrderDetailResDTO = new FulfillmentOrderDetailResDTO();
                BeanUtils.copyProperties(line, fulfillmentOrderDetailResDTO);
                fulfillmentOrderDetailResDTO.setFulfillmentDirectionType(order.getFulfillmentDirectionType());
                return fulfillmentOrderDetailResDTO;
            }).collect(Collectors.toList()));
        });
        resultDto.setSuccess(result.isSuccess());
        resultDto.setResult(fulfillmentOrderDetailDtoList);
        return resultDto;
    }

    @Override
    public Result<List<FulfillmentGetResDTO>> batchGet(FulfillmentOrderBatchGetRequest fulfillmentOrderBatchGetRequest){
        BatchGetReq batchGetReq = new BatchGetReq();
        BeanUtils.copyProperties(fulfillmentOrderBatchGetRequest, batchGetReq);
        log.info("batchGetReq参数:{}",JSON.toJSONString(batchGetReq));
        com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<List<FulfillmentGetRes>> result = fulfillmentOrderAbilityService.batchGet(batchGetReq);
        log.info("result履约结果:{}",JSON.toJSONString(result));
        Result<List<FulfillmentGetResDTO>> resultDto = new Result<>();
        if (CollectionUtils.isEmpty(result.getResult())) {
            resultDto.setSuccess(false);
            resultDto.setErrorCode("OC-01-004-01-16-002");
            resultDto.setMessage("查询履约单失败");
            return resultDto;
        }
        List<FulfillmentGetResDTO> fulfillmentGetResDTOList = new ArrayList<>();
        result.getResult().forEach(order -> {
            FulfillmentGetResDTO fulfillmentGetResDTO = new FulfillmentGetResDTO();
            BeanUtils.copyProperties(order, fulfillmentGetResDTO);
            List<FulfillmentDetailGetRes> detailList = order.getDetailList();
            List<FulfillmentDetailGetResDTO> fulfillmentDetailGetResDTOList = new ArrayList<>();
            detailList.forEach(detail -> {
                FulfillmentDetailGetResDTO fulfillmentDetailGetResDTO = new FulfillmentDetailGetResDTO();
                BeanUtils.copyProperties(detail, fulfillmentDetailGetResDTO);
                fulfillmentDetailGetResDTO.setFromSys(order.getFromSys());
                fulfillmentDetailGetResDTO.setBusinessType(order.getBusinessType());
                fulfillmentDetailGetResDTO.setBusinessUnitCode(order.getBusinessUnitCode());
                fulfillmentDetailGetResDTOList.add(fulfillmentDetailGetResDTO);
            });
            fulfillmentGetResDTO.setDetailList(fulfillmentDetailGetResDTOList);
            fulfillmentGetResDTOList.add(fulfillmentGetResDTO);
        });
        resultDto.setSuccess(result.isSuccess());
        resultDto.setResult(fulfillmentGetResDTOList);
        return resultDto;
    }


    @Override
    public Result<List<FulfillmentGetResDTO>> searchFulfillmentOrder(SearchFulfullmentOrderRequest searchFulfullmentOrderRequest){
        SearchFulfullmentOrderReq searchFulfullmentOrderReq = new SearchFulfullmentOrderReq();
        BeanUtils.copyProperties(searchFulfullmentOrderRequest, searchFulfullmentOrderReq);
        log.info("searchFulfullmentOrderReq参数:{}",JSON.toJSONString(searchFulfullmentOrderReq));
        com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<List<FulfillmentGetRes>> result = fulfillmentOrderAbilityService.searchFulfullmentOrder(searchFulfullmentOrderReq);
        log.info("result履约结果:{}",JSON.toJSONString(result));
        Result<List<FulfillmentGetResDTO>> resultDto = new Result<>();
        if (CollectionUtils.isEmpty(result.getResult())) {
            resultDto.setSuccess(false);
            resultDto.setErrorCode("OC-01-004-01-16-002");
            resultDto.setMessage("查询履约单失败");
            return resultDto;
        }
        List<FulfillmentGetResDTO> fulfillmentGetResDTOList = new ArrayList<>();
        result.getResult().forEach(order -> {
            FulfillmentGetResDTO fulfillmentGetResDTO = new FulfillmentGetResDTO();
            BeanUtils.copyProperties(order, fulfillmentGetResDTO);
            List<FulfillmentDetailGetRes> detailList = order.getDetailList();
            List<FulfillmentDetailGetResDTO> fulfillmentDetailGetResDTOList = new ArrayList<>();
            detailList.forEach(detail -> {
                FulfillmentDetailGetResDTO fulfillmentDetailGetResDTO = new FulfillmentDetailGetResDTO();
                BeanUtils.copyProperties(detail, fulfillmentDetailGetResDTO);
                fulfillmentDetailGetResDTO.setFromSys(order.getFromSys());
                fulfillmentDetailGetResDTO.setBusinessType(order.getBusinessType());
                fulfillmentDetailGetResDTO.setBusinessUnitCode(order.getBusinessUnitCode());
                fulfillmentDetailGetResDTOList.add(fulfillmentDetailGetResDTO);
            });
            fulfillmentGetResDTO.setDetailList(fulfillmentDetailGetResDTOList);
            fulfillmentGetResDTOList.add(fulfillmentGetResDTO);
        });
        resultDto.setSuccess(result.isSuccess());
        resultDto.setResult(fulfillmentGetResDTOList);
        return resultDto;
    }

    @Override
    public OrderAtomUpdateResponse cancelOrderInner(String salesOrderNo, String updater) {
        List<FulfillmentGetRes> fulfillmentGetResList = searchAllTypeFulfillmentOrder(salesOrderNo);
        if (CollectionUtils.isEmpty(fulfillmentGetResList)) {
            return null;
        }
        CancelOrderInnerReq cancelOrderInnerReq = new CancelOrderInnerReq();
        cancelOrderInnerReq.setUpdater(updater);
//        cancelOrderInnerReq.setReason(FulfillmentReasonEnum.UPDATE_CANCEL.getCode());
        for (FulfillmentGetRes fulfillmentGetRes : fulfillmentGetResList) {
            if (FulfillmentDetailStatusEnum.CANCEL.getValue().equals(Integer.valueOf(fulfillmentGetRes.getStatus())) || FulfillmentDetailStatusEnum.COMPLETE.getValue().equals(Integer.valueOf(fulfillmentGetRes.getStatus()))) {
                continue;
            }
            cancelOrderInnerReq.setFulfillmentOrderNo(fulfillmentGetRes.getFulfillmentOrderNo());
            com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<BatchCancelFulfillmentOrderResponse> cancelOrderInnerResult = fulfillmentOrderAbilityService.cancelOrderInner(cancelOrderInnerReq);
            log.info("FulfillmentOrderAbilityAdapterImpl#cancelOrderInner cancelOrderInnerReq:{}; cancelOrderInnerResult:{}", JSON.toJSONString(cancelOrderInnerReq), JSON.toJSONString(cancelOrderInnerResult));
            if (!cancelOrderInnerResult.isSuccess()) {
                return OrderAtomUpdateResponse.builder().errorCode(cancelOrderInnerResult.getErrorCode()).message(cancelOrderInnerResult.getMessage()).salesOrderNo(salesOrderNo).build();
            }
        }
        return null;
    }

    @Override
    public List<FulfillmentGetRes> searchAllTypeFulfillmentOrder(String salesOrderNo) {
        List<FulfillmentGetRes> result = new ArrayList<>();
        SearchFulfullmentOrderReq searchFulfullmentOrderReq = new SearchFulfullmentOrderReq();
        List<String> salesOrderNoList = new ArrayList<>();
        salesOrderNoList.add(salesOrderNo);
        searchFulfullmentOrderReq.setRefOrderNoList(salesOrderNoList);
        searchFulfullmentOrderReq.setFulfillmentDirectionType((FulfillmentDirectionTypeEnum.FORWARD.getValue()));
        com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<List<FulfillmentGetRes>> searchForwardResult = fulfillmentOrderAbilityService.searchFulfullmentOrder(searchFulfullmentOrderReq);
        searchFulfullmentOrderReq.setFulfillmentDirectionType((FulfillmentDirectionTypeEnum.REVERSE.getValue()));
        com.alibaba.cloud.retail.delivery.api.model.delivery.response.Result<List<FulfillmentGetRes>> searchReverseResult = fulfillmentOrderAbilityService.searchFulfullmentOrder(searchFulfullmentOrderReq);
        log.info("FulfillmentOrderAbilityAdapterImpl#searchAllTypeFulfillmentOrder searchForwardResult:{}; searchReverseResult:{}", JSON.toJSONString(searchForwardResult), JSON.toJSONString(searchReverseResult));
        if (!searchForwardResult.isSuccess() || !searchReverseResult.isSuccess()) {
            return result;
        }
        if(Objects.nonNull(searchForwardResult.getResult())){
            result.addAll(searchForwardResult.getResult());
        }
        if(Objects.nonNull(searchReverseResult.getResult())){
            result.addAll(searchReverseResult.getResult());
        }
        return result;
    }


}
